package cn.jlonely.xyhx.filter;

import cn.jlonely.xyhx.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取请求路径
        String path = request.getRequestURI();
        String authorizationHeader = request.getHeader("Authorization");

        // 判断是否是登录接口，直接放行
        if (path.contains("/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 判断是否是注册接口，直接放行
        if (path.contains("/register")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 判断是否是上传接口，直接放行
        if (path.contains("/upload")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 校验 Token 是否存在
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置 401 状态码
            response.setContentType("application/json;charset=utf-8");
            return;
        }

        // 提取 token 并校验
        String token = authorizationHeader.substring(7);  // 去掉 "Bearer " 部分
        try {
            JwtUtils.parseJwt(token); // 校验 JWT 是否有效
            filterChain.doFilter(request, response); // 放行请求
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); // 设置 401 状态码
            response.setContentType("application/json;charset=utf-8");
        }
    }
}
